package com.shaozi.nc.data.mongodao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import com.shaozi.nc.data.model.NoticeRecordNumModel;
import com.shaozi.data.mongo.dao.SZMongoBaseDao;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.utils.date.DateHelper;

@Repository("noticeRecordNumMDao")
public class NoticeRecordNumMDao extends SZMongoBaseDao<NoticeRecordNumModel> {

	@Autowired
	public NoticeRecordNumMDao(MongoTemplate shaoziTemplate) {
		super(shaoziTemplate);
	}

	public void save(NoticeRecordNumModel model) throws SzException {
		getMongoTemplate().save(model);
	}

	public void incCompanyId(String companyId, Integer type, int inc) {
		if (StringUtils.isEmpty(companyId))
			return;
		if (type == null)
			return;
		Criteria c = this.getIncCommon(type);
		c.and(NoticeRecordNumModel.FIELDNAME_companyId).is(companyId);
		incCommonUpsert(c, inc);
	}

	public void inc(Integer type, int inc) {
		if (type == null)
			return;
		Criteria c = this.getIncCommon(type);
		c.and(NoticeRecordNumModel.FIELDNAME_companyId).is(null);
		incCommonUpsert(c, inc);
	}

	private void incCommonUpsert(Criteria c, int inc) {
		Query query = new Query();
		query.addCriteria(c);
		Update update = new Update();
		update.inc(NoticeRecordNumModel.FIELDNAME_num, inc);
		long currentTime = System.currentTimeMillis();
		update.setOnInsert(NoticeRecordNumModel.FIELDNAME_createTime, currentTime);
		update.set(NoticeRecordNumModel.FIELDNAME_updateTime, currentTime);
		getMongoTemplate().upsert(query, update, NoticeRecordNumModel.class);
	}

	private Criteria getIncCommon(Integer type) {
		Criteria c = new Criteria(NoticeRecordNumModel.FIELDNAME_month).is(DateHelper.getMonth());
		c.and(NoticeRecordNumModel.FIELDNAME_type).is(type);
		c.and(NoticeRecordNumModel.FIELDNAME_year).is(DateHelper.getYearCurrent());
		return c;
	}

}
